<%- include('layout', { title: '注册', active: 'register' }) %>

<div class="max-w-md mx-auto">
    <div class="anime-card p-8">
        <div class="text-center mb-8">
            <i class="fas fa-user-plus text-6xl text-purple-500 mb-4"></i>
            <h1 class="text-3xl font-bold anime-gradient-text mb-2">创建账户</h1>
            <p class="text-gray-600">加入Minecraft面板，开始您的服务器管理之旅</p>
        </div>

        <form id="registerForm" class="space-y-6">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">用户名</label>
                <div class="relative">
                    <i class="fas fa-user absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                    <input type="text" name="username" required 
                           class="anime-input w-full pl-10" 
                           placeholder="请输入用户名">
                </div>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">邮箱</label>
                <div class="relative">
                    <i class="fas fa-envelope absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                    <input type="email" name="email" required 
                           class="anime-input w-full pl-10" 
                           placeholder="请输入邮箱地址">
                </div>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">密码</label>
                <div class="relative">
                    <i class="fas fa-lock absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                    <input type="password" name="password" required 
                           class="anime-input w-full pl-10" 
                           placeholder="请输入密码">
                    <button type="button" id="togglePassword" 
                            class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600">
                        <i class="fas fa-eye"></i>
                    </button>
                </div>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">确认密码</label>
                <div class="relative">
                    <i class="fas fa-lock absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                    <input type="password" name="confirm_password" required 
                           class="anime-input w-full pl-10" 
                           placeholder="请再次输入密码">
                </div>
            </div>

            <div class="flex items-center">
                <input type="checkbox" id="agreeTerms" required 
                       class="rounded border-gray-300 text-purple-600 focus:ring-purple-500">
                <label for="agreeTerms" class="ml-2 text-sm text-gray-600">
                    我同意 <a href="#" class="text-purple-600 hover:text-purple-500">服务条款</a> 和 <a href="#" class="text-purple-600 hover:text-purple-500">隐私政策</a>
                </label>
            </div>

            <button type="submit" id="registerButton" 
                    class="anime-button w-full py-3 text-lg font-semibold">
                <i class="fas fa-user-plus mr-2"></i>注册账户
            </button>
        </form>

        <div class="mt-6 text-center">
            <p class="text-sm text-gray-600">
                已有账户？
                <a href="/login" class="text-purple-600 hover:text-purple-500 font-medium">立即登录</a>
            </p>
        </div>
    </div>
</div>

<script>
// 密码显示/隐藏切换
document.getElementById('togglePassword').addEventListener('click', function() {
    const passwordInput = document.querySelector('input[name="password"]');
    const icon = this.querySelector('i');
    
    if (passwordInput.type === 'password') {
        passwordInput.type = 'text';
        icon.className = 'fas fa-eye-slash';
    } else {
        passwordInput.type = 'password';
        icon.className = 'fas fa-eye';
    }
});

// 实时密码强度检查
document.querySelector('input[name="password"]').addEventListener('input', function() {
    const password = this.value;
    const strength = checkPasswordStrength(password);
    
    // 可以在这里添加密码强度显示逻辑
});

function checkPasswordStrength(password) {
    let strength = 0;
    if (password.length >= 8) strength++;
    if (password.match(/[a-z]/) && password.match(/[A-Z]/)) strength++;
    if (password.match(/[0-9]/)) strength++;
    if (password.match(/[^a-zA-Z0-9]/)) strength++;
    
    return strength;
}

// 表单提交处理
document.getElementById('registerForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const data = Object.fromEntries(formData);
    
    // 验证密码
    if (data.password !== data.confirm_password) {
        showAlert('密码不匹配', 'error');
        return;
    }
    
    if (data.password.length < 6) {
        showAlert('密码长度至少为6位', 'error');
        return;
    }
    
    // 验证邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(data.email)) {
        showAlert('邮箱格式不正确', 'error');
        return;
    }
    
    // 验证用户名格式
    const usernameRegex = /^[a-zA-Z0-9_]{3,20}$/;
    if (!usernameRegex.test(data.username)) {
        showAlert('用户名只能包含字母、数字和下划线，长度3-20位', 'error');
        return;
    }
    
    // 禁用按钮
    const button = document.getElementById('registerButton');
    button.disabled = true;
    button.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>注册中...';
    
    try {
        const response = await fetch('/auth/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (result.success) {
            showAlert(result.message || '注册成功！', 'success');
            setTimeout(() => {
                window.location.href = '/login';
            }, 2000);
        } else {
            showAlert(result.error || '注册失败', 'error');
            button.disabled = false;
            button.innerHTML = '<i class="fas fa-user-plus mr-2"></i>注册账户';
        }
    } catch (error) {
        showAlert('注册失败：' + error.message, 'error');
        button.disabled = false;
        button.innerHTML = '<i class="fas fa-user-plus mr-2"></i>注册账户';
    }
});

// 检查是否已经登录
document.addEventListener('DOMContentLoaded', async function() {
    try {
        const response = await fetch('/auth/check');
        const result = await response.json();
        
        if (result.logged_in) {
            window.location.href = '/dashboard';
        }
    } catch (error) {
        console.log('未登录状态');
    }
});

// 用户名可用性检查
document.querySelector('input[name="username"]').addEventListener('blur', async function() {
    const username = this.value.trim();
    if (username.length < 3) return;
    
    try {
        const response = await fetch('/auth/check-username', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username })
        });
        
        const result = await response.json();
        
        if (result.available === false) {
            showAlert('用户名已被使用', 'error');
            this.focus();
        }
    } catch (error) {
        console.log('用户名检查失败');
    }
});

// 邮箱可用性检查
document.querySelector('input[name="email"]').addEventListener('blur', async function() {
    const email = this.value.trim();
    if (!email) return;
    
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) return;
    
    try {
        const response = await fetch('/auth/check-email', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ email })
        });
        
        const result = await response.json();
        
        if (result.available === false) {
            showAlert('邮箱已被注册', 'error');
            this.focus();
        }
    } catch (error) {
        console.log('邮箱检查失败');
    }
});
</script>

<%- scripts %>